package com.vf.editor.mvc.resources.scene;

import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.vf.editor.common.controller.BaseController;
import com.vf.editor.common.model.resources.Scene;
import com.vf.editor.common.model.resources.SceneConfig;
import com.vf.editor.common.plugins.shiro.ShiroKit;
import com.vf.editor.common.plugins.shiro.SimpleUser;
import com.vf.editor.common.util.UuidUtil;

@Path(value = "/resources/scene", viewPath = "/views/resources/scene/")
public class SceneContoller extends BaseController {

	public void index() {
		render("list.html");
	}

	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String isPublic = getPara("isPublic");

		String userId = "";
		SimpleUser simpleUser = ShiroKit.getLoginUser();
		if (simpleUser != null && StrKit.equals(simpleUser.getUsername(), "system")) {
			userId = simpleUser.getId();
		}

		String sqlExceptSelect = " FROM " + Scene.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%' ) ";
		}

		if (StrKit.equals("1", isPublic)) {
			sqlExceptSelect += " and o.createUserId = '" + userId + "'   ";
		} else if (StrKit.equals("0", isPublic)) {
			sqlExceptSelect += " and o.isPublic = '0'   ";
		} else {
			sqlExceptSelect += " and ( o.createUserId = '" + userId + "' or  o.isPublic = '0' ) ";
		}

		sqlExceptSelect += "  ORDER BY   O.CREATETIME desc ";
		Page<Scene> page = Scene.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}

	/***
	 * 保存
	 */
	public void save() {
		Scene model = getModel(Scene.class);
		if (StrKit.notBlank(model.getId())) {
			if (model.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			SimpleUser simpleUser = ShiroKit.getLoginUser();
			if (simpleUser == null) {
				renderError("会话过期，退出重新登录！！！");
				return;
			}
			model.setCreateUserId(simpleUser.getId());
			model.setId(UuidUtil.getUUID());
			if (model.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}

	}

	/***
	 * 删除
	 * @throws Exception
	 */
	@Before(Tx.class)
	public void delete() throws Exception {
		String id = getPara("id");
		Scene model = Scene.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				SceneConfig.dao.deleteById(id);
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}

	public void findById() throws Exception {
		String id = getPara("id");
		Scene model = Scene.dao.findById(id);
		if (model != null) {
			renderSuccess("成功！", model);
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}

}
